package com.asr.service;

import com.asr.config.AsrProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
@RequiredArgsConstructor
public class FileService {
    
    private final AsrProperties asrProperties;
    private final SshService sshService;
    
    private static final List<String> AUDIO_EXTENSIONS = List.of(
        ".wav", ".mp3", ".flac", ".ogg", ".m4a", ".aac", ".wma"
    );
    
    /**
     * 上传音频文件
     */
    public String uploadAudioFile(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !isAudioFile(originalFilename)) {
            throw new IllegalArgumentException("不支持的文件格式");
        }
        
        // 生成唯一文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;
        
        // 如果启用远程服务器
        if (asrProperties.getRemote() != null && asrProperties.getRemote().getEnabled()) {
            String remotePath = asrProperties.getAudioUploadDir() + "/" + filename;
            sshService.uploadFile(file, remotePath);
            log.info("上传文件到远程服务器: {} -> {}", originalFilename, remotePath);
            return remotePath;
        } else {
            // 本地保存
            Path uploadDir = Paths.get(asrProperties.getAudioUploadDir());
            Files.createDirectories(uploadDir);
            Path filePath = uploadDir.resolve(filename);
            file.transferTo(filePath.toFile());
            log.info("上传文件到本地: {} -> {}", originalFilename, filePath);
            return filePath.toString();
        }
    }
    
    /**
     * 批量上传音频文件
     */
    public List<String> uploadAudioFiles(List<MultipartFile> files) throws Exception {
        List<String> filePaths = new ArrayList<>();
        for (MultipartFile file : files) {
            filePaths.add(uploadAudioFile(file));
        }
        return filePaths;
    }
    
    /**
     * 列出指定目录下的音频文件
     */
    public List<String> listAudioFiles(String directory) throws IOException {
        Path dir = Paths.get(directory);
        if (!Files.exists(dir) || !Files.isDirectory(dir)) {
            return new ArrayList<>();
        }
        
        try (Stream<Path> paths = Files.walk(dir)) {
            return paths
                .filter(Files::isRegularFile)
                .filter(path -> isAudioFile(path.getFileName().toString()))
                .map(Path::toString)
                .collect(Collectors.toList());
        }
    }
    
    /**
     * 列出上传目录下的音频文件
     */
    public List<String> listUploadedAudioFiles() throws IOException {
        return listAudioFiles(asrProperties.getAudioUploadDir());
    }
    
    /**
     * 删除文件
     */
    public boolean deleteFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            Files.deleteIfExists(path);
            log.info("删除文件: {}", filePath);
            return true;
        } catch (IOException e) {
            log.error("删除文件失败: {}", filePath, e);
            return false;
        }
    }
    
    /**
     * 获取文件信息
     */
    public FileInfo getFileInfo(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            return null;
        }
        
        FileInfo info = new FileInfo();
        info.setPath(filePath);
        info.setName(path.getFileName().toString());
        info.setSize(Files.size(path));
        info.setLastModified(Files.getLastModifiedTime(path).toMillis());
        
        return info;
    }
    
    /**
     * 判断是否为音频文件
     */
    private boolean isAudioFile(String filename) {
        String lowerFilename = filename.toLowerCase();
        return AUDIO_EXTENSIONS.stream().anyMatch(lowerFilename::endsWith);
    }
    
    /**
     * 文件信息类
     */
    public static class FileInfo {
        private String path;
        private String name;
        private Long size;
        private Long lastModified;
        
        // Getters and Setters
        public String getPath() { return path; }
        public void setPath(String path) { this.path = path; }
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public Long getSize() { return size; }
        public void setSize(Long size) { this.size = size; }
        
        public Long getLastModified() { return lastModified; }
        public void setLastModified(Long lastModified) { this.lastModified = lastModified; }
    }
}
